import re
import serial
import logging


logger = logging.getLogger(__name__)

class SerialBase:
    def __init__(self, name : str = None, rate: int = None, timeout: float = None):
        self.name = name
        self.rate = rate
        self.timeout = timeout
        self.serial = None

    def loadconfig(self, config: dict = None):
        try:
            self.name = config["name"]
            self.rate = config["Baud-rate"]
            self.timeout = config["timeout"]
            logger.info("Success to load serial connect config")
        except:
            logger.error("Failed to load serial connect config ")

    def InitConnect(self):
        if self.name is not None and self.rate is not None and self.timeout is not None:
            try:
                self.serial = serial.Serial(self.name, self.rate, timeout=self.timeout)
                logger.info(f"Success to connect {self.name}")
            except:
                logger.error(f"Failed to connect {self.name}")
                return False
        else:
            logger.error(f"Failed to connect {self.name}")
            return False

    def close(self):
        if self.serial is not None:
            self.serial.close()
            return True
        else:
            return False

    def send(self, messages: str = None):
        if self.serial is None:
            self.InitConnect()
        self.serial.write(bytes(messages, encoding='UTF-8'))

    def receive(self):
        if self.serial is None:
            self.InitConnect()
        self.serial.flushInput()
        data = self.serial.readline()
        Dcoder = data.decode()[:-2]
        return Dcoder
